import pandas as pd
from sklearn.model_selection import train_test_split,GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
import joblib
# 1.获取数据集
data = pd.read_csv('/Users/lyn/Desktop/数据集/FaceBook_train.csv')
# 2.基本数据处理
# 2.1缩小数据特征
partial_data = data.query('x >2.0& x <2.5& y >2.0& y <2.5').copy()
# 2.2选择时间特征
time = pd.to_datetime(partial_data["time"],unit = "s")
# 假设 time 是与 partial_data 索引对齐的 DatetimeIndex
time = pd.DatetimeIndex(time)
partial_data.loc[:, "hour"] = time.hour
partial_data.loc[:, "day"] = time.day
partial_data.loc[:, "weekday"] = time.weekday
# 2.3去掉签到较少的地方
place_count = partial_data.groupby("place_id").count()
place_count = place_count[place_count["row_id"]>3]
partial_data = partial_data[partial_data["place_id"].isin(place_count.index)]
# 2.4确定特征值和目标值，x为特征值，y为目标值
x = partial_data[["x","y","accuracy","hour","day","weekday"]]
y = partial_data["place_id"]
# 2.5分割数据集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=2)
# 3.特征工程-特征预处理（标准化）
transformer = StandardScaler()
x_train = transformer.fit_transform(x_train)
x_test = transformer.transform(x_test)
# 4.机器学习-KNN+cv
#4.1实例化一个训练器
estimator = KNeighborsClassifier()
# 4.2交叉验证，网格搜索实现
param_grid = {"n_neighbors":[3,5,7,9]}
estimator = GridSearchCV(estimator = estimator,param_grid=param_grid,cv=10,n_jobs=-1)# n_jobs是设置几个cup，可以让代码跑的快
# 4.3模型训练
estimator.fit(x_train,y_train)
# 4.4保存模型
joblib.dump(estimator,'/Users/lyn/Desktop/数据集/模型保存.pkl')
# 4.4模型加载
#estimator = joblib.load('/Users/lyn/Desktop/数据集/Facebook模型保存.pkl')
# 5.模型评估
# 5.1准确率输出
print("准确率输出：")
print(estimator.score(x_test,y_test))
print()
# 5.2预测结果
print("预测结果：")
print(estimator.predict(x_test))
print()
# 5.3其他结果输出
#最好的模型是
print("最好的模型是：")
print(estimator.best_estimator_.get_params())
print()
# 最好的结果是
print("最好的结果是：")
print(estimator.best_score_)
print()
# 所有的结果是
print("所有的结果是：")
print(estimator.cv_results_)
print()